package com.da.lon.wang.xlg.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.adapter.OrderAdapter;
import com.da.lon.wang.xlg.adapter.OrderAdapter.CallBack1;
import com.da.lon.wang.xlg.bean.CheckBean;
import com.da.lon.wang.xlg.bean.CheckInfoResultBean;
import com.da.lon.wang.xlg.bean.CheckInfoResultBean.OrderAddress;
import com.da.lon.wang.xlg.bean.CheckInfoResultBean.cart_result;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.osell.selection.util.DeviceUuidFactory;
import com.umeng.analytics.MobclickAgent;

import net.tsz.afinal.http.AjaxParams;

import java.util.ArrayList;

/**
 * 订单
 */
public class OrderActivity extends BaseActivity implements OnClickListener,
        CallBack1 {
    private Context context = null;

    private ImageButton backButton;

    private String user_id;
    private String deviceId;
    private String user_key;

    private HttpLoader<CheckBean> loader2;

    private int requestCode;

    private TextView allpriceView;
    private Button allButton;

    private String addid = null;
    private String bodynumber = null;

    private TextView titleView;

    private ListView orderListView;
    private OrderAdapter adapter;

    private String ids = null;
    private String needCoordinates = null;
    private String data_store = null;
    private String couponId = null;
    private String couponcount = null;
    private String invoiceString = null;
    private String isinvoice = null;
    private String dqmoney = null;
    private String totalAmount = null;
    private String totalCount = null;
    private String pro_type = null;
    private String area_type = null;
    private String invoice_type = null;
    private String invoice_up = null;
    private StringBuffer qcontent = new StringBuffer();

    // 存储信息的集合
    private ArrayList<cart_result> datas;
    private OrderAddress orderAddress;

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ouka_order);
        context = this;

        datas = new ArrayList<>();

        titleView = (TextView) findViewById(R.id.title);
        titleView.setText(R.string.place_order_2);
        backButton = (ImageButton) findViewById(R.id.ouka_home_buyer_left);
        backButton.setOnClickListener(this);
        allButton = (Button) findViewById(R.id.order_all_button);
        allButton.setOnClickListener(this);
        orderListView = (ListView) findViewById(R.id.ouka_order_lv);
        allpriceView = (TextView) findViewById(R.id.order_all_price);

    }

    @Override
    protected void onStart() {
        super.onStart();

        user_id = PreferenceUtils.getInstance().getSettingStr(
                PreferencesConfig.USER_ID, "");
        deviceId = new DeviceUuidFactory(this).getDeviceUuid().toString();
        user_key = PreferenceUtils.getInstance().getSettingStr(
                PreferencesConfig.USER_KEY, "");

        Bundle bundle = this.getIntent().getExtras();
        if (null != bundle) {
            ids = bundle.getString("ids");
            needCoordinates = bundle.getString("needCoordinates");
            data_store = bundle.getString("data_store");
            getData(ids, needCoordinates, data_store);
        }

    }

    /**
     * 获取界面上的数据
     *
     * @param ids
     * @param needCoordinates
     * @param data_store
     */
    private void getData(String ids, String needCoordinates, String data_store) {

        try {
            if (ids != null && !"".equals(ids)) {
                String url = XLGConstants.URL + XLGConstants.URL_CART_HRAD
                        + XLGConstants.URL_CHOISE;
                HttpLoader<CheckInfoResultBean> loader = new HttpLoader<CheckInfoResultBean>(
                        context, url, CheckInfoResultBean.class);
                AjaxParams params = new AjaxParams();
                params.put(
                        "token",
                        XLGDataUtils.encrypt2MD5("Cart" + XLGConstants.SECRET
                                + XLGConstants.URL_CHOISE));
                params.put("id", user_id);
                params.put("user_key", user_key);
                params.put("ids", ids);
                if (addid != null && !"".equals(addid)) {
                    params.put("addid", addid);
                }
                if (data_store != null && !"".equals(data_store)) {
                    params.put("data_store", data_store);
                }
                if (couponId != null && !"".equals(couponId)) {
                    params.put("couponid", couponId);
                }
                params.put("needCoordinates", needCoordinates);
                params.put("deviceId", deviceId);
                loader.loadData(params);
                loader.setManagerListener(new OnWebLoadListener<CheckInfoResultBean>() {

                    @Override
                    public void OnStart() {
                        showDialog();
                    }

                    @Override
                    public void OnError(String error) {
                        dismissDialog();
                    }

                    @Override
                    public void onSuccess(CheckInfoResultBean t) {
                        dismissDialog();
                        if (t != null && "000000".equals(t.getCode())) {

                            datas = t.getResult().getCart_result();
                            orderAddress = t.getResult().getAddress();
                            couponcount = t.getResult().getCouponcount();
                            isinvoice = t.getResult().getIsinvoice();
                            dqmoney = t.getResult().getDqmoney();
                            totalAmount = t.getResult().getTotalAmount();
                            totalCount = t.getResult().getTotalCount();

                            if (t.getResult().getPro_type() != null) {
                                pro_type = t.getResult().getPro_type();
                            }

                            if (t.getResult().getArea_type() != null) {
                                area_type = t.getResult().getArea_type();
                            }

                            if (totalAmount != null) {
                                allpriceView.setText("实付款: ￥" + totalAmount);
                            }

                            if (orderAddress != null) {
                                addid = orderAddress.getAdd_id();
                                bodynumber = orderAddress.getBody_card_number();
                            }
                            if (datas != null) {
                                adapter = new OrderAdapter(context, datas,
                                        orderAddress, couponcount, couponId,
                                        isinvoice, invoiceString, dqmoney,
                                        totalAmount, totalCount,
                                        OrderActivity.this);
                                orderListView.setAdapter(adapter);
                            }

                        }
                    }
                });
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ouka_home_buyer_left:
                finish();
                break;
            case R.id.order_all_button:
                try {
                    if (data_store != null && "-1".equals(data_store)) {

                        if (addid != null && !"".equals(addid)) {
                            if ("0".equals(pro_type)) {

                                loader2 = new HttpLoader<CheckBean>(this,
                                        XLGConstants.URL + "/Cart-checkout",
                                        CheckBean.class, 60 * 1000);

                                AjaxParams params11 = new AjaxParams();

                                params11.put("token", XLGDataUtils
                                        .encrypt2MD5("Cart" + "2015#$%"
                                                + "checkout"));
                                params11.put("user_key", user_key);
                                params11.put("id", user_id);
                                params11.put("ids", ids);

                                params11.put("qcontent", "{" + getcontent() + "}");
                                params11.put("addid", addid);
                                params11.put("area_type", area_type);
                                params11.put("deviceId", deviceId);
                                params11.put("version", "21");
                                params11.put("couponid", couponId);
                                if (data_store != null && !"".equals(data_store)) {
                                    params11.put("data_store", data_store);
                                }
                                if (invoice_type != null
                                        && !"".equals(invoice_type)) {
                                    params11.put("invoice_type", invoice_type);
                                } else {
                                    params11.put("invoice_type", "0");
                                }
                                if (invoice_up != null && !"".equals(invoice_up)) {
                                    params11.put("invoice_up", invoice_up);
                                } else {
                                    params11.put("invoice_up", "");
                                }
                                params11.put("pro_type", pro_type);

                                loader2.setManagerListener(new OnWebLoadListener<CheckBean>() {

                                    @Override
                                    public void OnStart() {
                                        // TODO Auto-generated method stub
                                    }

                                    @Override
                                    public void OnError(String error) {
                                        // TODO Auto-generated method stub
                                    }

                                    @Override
                                    public void onSuccess(CheckBean t) {
                                        // TODO Auto-generated method stub
                                        if (t != null
                                                && t.getCode().equals("000000")) {
                                            Intent intent = new Intent(
                                                    OrderActivity.this,
                                                    WebViewActivity.class);
                                            Bundle bundle = new Bundle();
                                            bundle.putString("url", t.getResult());
                                            bundle.putInt("flag", 1800);
                                            intent.putExtras(bundle);
                                            startActivity(intent);
                                        } else {
                                            Toast.makeText(OrderActivity.this,
                                                    t.getMessage(),
                                                    Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });

                                loader2.loadData(params11);
                            } else {
                                if (bodynumber == null || bodynumber.equals("")
                                        || bodynumber.equals("false")) {
                                    Toast.makeText(OrderActivity.this,
                                            "亲,收货地址必须要身份证号码,请填写身份证号码!",
                                            Toast.LENGTH_SHORT).show();
                                } else {

                                    loader2 = new HttpLoader<CheckBean>(this,
                                            XLGConstants.URL + "/Cart-checkout",
                                            CheckBean.class, 60 * 1000);

                                    AjaxParams params11 = new AjaxParams();

                                    params11.put("token", XLGDataUtils
                                            .encrypt2MD5("Cart" + "2015#$%"
                                                    + "checkout"));
                                    params11.put("user_key", user_key);
                                    params11.put("id", user_id);
                                    params11.put("ids", ids);
                                    params11.put("qcontent", "{" + getcontent()
                                            + "}");
                                    params11.put("addid", addid);
                                    params11.put("area_type", area_type);
                                    params11.put("deviceId", deviceId);
                                    params11.put("version", "21");
                                    params11.put("couponid", couponId);
                                    if (data_store != null
                                            && !"".equals(data_store)) {
                                        params11.put("data_store", data_store);
                                    }
                                    if (invoice_type != null
                                            && !"".equals(invoice_type)) {
                                        params11.put("invoice_type", invoice_type);
                                    } else {
                                        params11.put("invoice_type", "0");
                                    }
                                    if (invoice_up != null
                                            && !"".equals(invoice_up)) {
                                        params11.put("invoice_up", invoice_up);
                                    } else {
                                        params11.put("invoice_up", "");
                                    }
                                    params11.put("pro_type", pro_type);

                                    loader2.setManagerListener(new OnWebLoadListener<CheckBean>() {

                                        @Override
                                        public void OnStart() {
                                            // TODO Auto-generated method stub
                                        }

                                        @Override
                                        public void OnError(String error) {
                                            // TODO Auto-generated method stub
                                        }

                                        @Override
                                        public void onSuccess(CheckBean t) {
                                            // TODO Auto-generated method stub
                                            if (t != null
                                                    && t.getCode().equals("000000")) {
                                                Intent intent = new Intent(
                                                        OrderActivity.this,
                                                        WebViewActivity.class);
                                                Bundle bundle = new Bundle();
                                                bundle.putString("url",
                                                        t.getResult());
                                                bundle.putInt("flag", 1800);
                                                intent.putExtras(bundle);
                                                startActivity(intent);
                                            } else {
                                                Toast.makeText(OrderActivity.this,
                                                        t.getMessage(),
                                                        Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });

                                    loader2.loadData(params11);
                                }
                            }
                        } else {
                            Toast.makeText(OrderActivity.this, "亲,请去添加收货地址!",
                                    Toast.LENGTH_SHORT).show();
                        }
                    } else {

                        loader2 = new HttpLoader<CheckBean>(this, XLGConstants.URL
                                + "Cart-checkout", CheckBean.class, 60 * 1000);

                        AjaxParams params11 = new AjaxParams();

                        params11.put("token", XLGDataUtils.encrypt2MD5("Cart"
                                + "2015#$%" + "checkout"));
                        params11.put("user_key", user_key);
                        params11.put("id", user_id);
                        params11.put("ids", ids);
                        params11.put("qcontent", "{" + getcontent() + "}");
                        params11.put("addid", "");
                        params11.put("area_type", area_type);
                        params11.put("deviceId", deviceId);
                        params11.put("version", "21");
                        params11.put("couponid", couponId);
                        if (data_store != null && !"".equals(data_store)) {
                            params11.put("data_store", data_store);
                        }
                        if (invoice_type != null && !"".equals(invoice_type)) {
                            params11.put("invoice_type", invoice_type);
                        } else {
                            params11.put("invoice_type", "0");
                        }
                        if (invoice_up != null && !"".equals(invoice_up)) {
                            params11.put("invoice_up", invoice_up);
                        } else {
                            params11.put("invoice_up", "");
                        }
                        params11.put("pro_type", pro_type);

                        loader2.setManagerListener(new OnWebLoadListener<CheckBean>() {

                            @Override
                            public void OnStart() {

                            }

                            @Override
                            public void OnError(String error) {

                            }

                            @Override
                            public void onSuccess(CheckBean t) {
                                if (t != null && t.getCode().equals("000000")) {

                                    Intent intent = new Intent(OrderActivity.this,
                                            WebViewActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putString("url", t.getResult());
                                    bundle.putInt("flag", 1800);
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                } else {
                                    Toast.makeText(OrderActivity.this,
                                            t.getMessage(), Toast.LENGTH_SHORT)
                                            .show();
                                }
                            }
                        });

                        loader2.loadData(params11);
                    }

                    MyApplication.addActivity(this);
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }

                break;

            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub

        if (data != null) {
            String addid1 = data.getStringExtra("addid");
            String bodynumber1 = data.getStringExtra("bodynumber");
            String couponid = data.getStringExtra("couponId");
            String invoice = data.getStringExtra("invoice");
            String invoiceText = data.getStringExtra("invoiceText");
            String invoiceType = data.getStringExtra("invoiceType");

            switch (resultCode) {
                case 0:

                    addid = addid1;

                    break;

                case 1:

                    addid = addid1;

                    bodynumber = bodynumber1;

                    break;
                case 2:

                    couponId = couponid;

                    break;
                case 3:

                    invoiceString = invoice;
                    invoice_type = invoiceType;
                    invoice_up = invoiceText;

                    break;

                default:
                    break;
            }

        }
    }

    @Override
    public void click(View v) {
        switch (v.getId()) {
            case R.id.order_address:
                // 有收货地址的时候
                if (addid != null && !"".equals(addid)) {
                    requestCode = 0;
                    Intent intent1 = new Intent(OrderActivity.this,
                            AddressActivity.class);
                    intent1.putExtra("addid", addid);
                    intent1.putExtra("pro_type", pro_type);
                    startActivityForResult(intent1, requestCode);
                }
                break;
            case R.id.address_null:
                // 没有收货地址的时候
                requestCode = 1;
                Intent intent11 = new Intent(OrderActivity.this,
                        EditAddressActivity.class);
                // 自动定位
                intent11.putExtra("key", 0);
                // 身份证号码 0 为不需要 其他为需要身份证号！
                intent11.putExtra("pro_type", pro_type);
                startActivityForResult(intent11, requestCode);
                break;
            case R.id.order_coupon_check:
                // 优惠券
                requestCode = 2;
                Intent intent = new Intent(this, CouponActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("ids", ids);
                bundle.putString("data_store", data_store);
                intent.putExtras(bundle);
                startActivityForResult(intent, requestCode);
                break;
            case R.id.order_bill_check:
                // 发票信息
                requestCode = 3;
                Intent intent2 = new Intent(this, InvoiceActivity.class);
                intent2.putExtra("invoice", invoiceString);
                intent2.putExtra("invoiceText", invoice_up);
                intent2.putExtra("invoiceType", invoice_type);
                startActivityForResult(intent2, requestCode);
            default:
                break;
        }
    }

    public StringBuffer getcontent() {

        ArrayList<cart_result> datas2 = MyApplication.getInstance()
                .getDatas();
        for (int position = 0; datas2 != null && position < datas2.size(); position++) {
            String key = datas.get(position).getValue().get(0).getPone()
                    .getStore_id()
                    + datas.get(position).getValue().get(0).getPone()
                    .getSales_type() + datas.get(position).getAr();
            cart_result cart_result = datas.get(position);
            String leave_message = cart_result.getLeave_message();
            qcontent.append(key + "=" + leave_message != null ? leave_message
                    : "" + ";");
        }


        return qcontent;

    }

}
